package com.dragon.modules.yuegou.service.impl.live;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.client.wechat_mini.common.MiniConfig;
import com.dragon.modules.yuegou.client.wechat_mini.request.RoomCreateRequest;
import com.dragon.modules.yuegou.client.wechat_mini.response.MediaUploadResponse;
import com.dragon.modules.yuegou.client.wechat_mini.response.RoomCreateResponse;
import com.dragon.modules.yuegou.client.wechat_mini.service.MiniService;
import com.dragon.modules.yuegou.client.wechat_mini.service.impl.MiniServiceImpl;
import com.dragon.modules.yuegou.entity.live.BroadcastEntity;
import com.dragon.modules.yuegou.enums.code.LiveCode;
import com.dragon.modules.yuegou.mapper.live.BroadcastMapper;
import com.dragon.modules.yuegou.model.live.Broadcast;
import com.dragon.modules.yuegou.model.system.Application;
import com.dragon.modules.yuegou.properties.LiveProperties;
import com.dragon.modules.yuegou.query.live.BroadcastQuery;
import com.dragon.modules.yuegou.service.live.BroadcastService;
import com.dragon.modules.yuegou.service.product.PostersService;
import com.dragon.modules.yuegou.service.system.ApplicationService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

/**
 * 直播间信息表 服务实现
 *
 * @author ZSH
 * @date 2020-06-05 17:40:15
 * @version 2.0
 */
@Slf4j
@Service("liveBroadcastService")
public class BroadcastServiceImpl extends ServiceImpl<BroadcastMapper, BroadcastEntity>
		implements BroadcastService {

	@Autowired
	private ApplicationService applicationService;

	@Autowired
	private LiveProperties liveProperties;

	@Autowired
	private PostersService postersService;

	@Override
	public IPage<Broadcast> search(PageRequest page, String name, String roomId, String busdId) {
		BroadcastQuery query = new BroadcastQuery();
		query.name().like(name);
		query.busdId().eq(busdId);
		query.roomId().like(roomId);
		query.setDel(false);
		QueryWrapper<BroadcastEntity> wrapper = query.toQueryWrapper();

		wrapper.orderByAsc(BroadcastQuery.COL_LIVE_STATUS);
		wrapper.orderByDesc(BroadcastQuery.COL_CREATED_TIME);
		IPage<BroadcastEntity> entityIPage =  baseMapper.selectPage(PageToResultUtils.resultToPage(page), wrapper);

		return entityIPage.convert(Broadcast::new);
	}

	@Override
	public void saveBroa(Broadcast broadcast) {
		//校验直播开始结束时间
		if (broadcast.getBeginTime().minusMinutes(30l).isBefore(LocalDateTime.now())) {
			throw new DragonException(LiveCode.INCORRECT_LIVE_TIME);
		}
		Duration duration = Duration.between(broadcast.getBeginTime(),broadcast.getEndTime());
		if (duration.toMinutes() < 30 || duration.toHours() >= 12) {
			throw new DragonException(LiveCode.INCORRECT_LIVE_TIME);
		}
		// 查询application信息
		Application application = applicationService.getOriginalId(broadcast.getBusdId());
		MiniService service = new MiniServiceImpl(new MiniConfig(application.getAppid(), application.getAppsecret()));
		//构建请求
		RoomCreateRequest request = new RoomCreateRequest();
		request.setAnchorName(broadcast.getAnchorName());
		request.setAnchorWechat(broadcast.getAnchorWechat());
		request.setEndTime(broadcast.getEndTime().toEpochSecond(ZoneOffset.of("+8")));
		request.setStartTime(broadcast.getBeginTime().toEpochSecond(ZoneOffset.of("+8")));
		request.setName(broadcast.getName());
		request.setCoverImg(broadcast.getCoverImgMedia());
		request.setShareImg(broadcast.getShareImgMedia());
		request.setFeedsImg(broadcast.getFeedsImgMedia());
		request.setCloseLike(broadcast.getCloseLike()?1:0);
		request.setCloseGoods(broadcast.getCloseGoods()?1:0);
		request.setCloseComment(broadcast.getCloseComment()?1:0);

		log.debug(JSON.toJSONString(request));
		//创建直播间
		RoomCreateResponse response = service.live().roomCreate(request);
		if (response !=null &&response.getErrcode() !=null && response.getErrcode() !=0){
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),response.getErrmsg()));
		}

		//创建直播间
		broadcast.setRoomId(response.getRoomId());
		baseMapper.insert(broadcast);
	}

	@Override
	public void deleteBroa(String broadcastId) {
		// 获得直播间信息
		BroadcastEntity broadcast = getById(broadcastId);
		broadcast.setDel(true);
		baseMapper.updateById(broadcast);
	}

	@Override
	public String generateCode(String broadcastId, String busdId) {
		Broadcast broadcast = this.broadDetails(broadcastId);
		if (broadcast==null || StringUtils.isBlank(broadcast.getRoomId())){
			throw new DragonException(LiveCode.ROOM_NOT_EXIST);
		}
		// 查询application信息
		Application application = applicationService.getOriginalId(busdId);
		String path = String.format(liveProperties.getGenerate(), broadcast.getRoomId());
		return postersService.getMiniCode(path, application.getAppid(), application.getAppsecret());
	}

	@Override
	public Broadcast broadDetails(String broadcastId) {
		return new Broadcast(getById(broadcastId));
	}

	@Override
	public String wxUpload(MultipartFile file, String busdId) {
		// 查询application信息
		Application application = applicationService.getOriginalId(busdId);

		// 获取文件名
		String fileName = file.getOriginalFilename();
		// 获取文件后缀
		String prefix = fileName.substring(fileName.lastIndexOf("."));
		// 用uuid作为文件名，防止生成的临时文件重复
		File tempFile;
		try {
			tempFile = File.createTempFile(System.currentTimeMillis() + "", prefix);
			file.transferTo(tempFile);
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
		MiniService service = new MiniServiceImpl(new MiniConfig(application.getAppid(), application.getAppsecret()));
		MediaUploadResponse response =service.live().mediaUploadImage(tempFile);

		// 删除临时文件
		if (tempFile.exists()) {
			tempFile.delete();
		}

		if (response !=null &&response.getErrcode() !=null && response.getErrcode() !=0){
			throw new DragonException(LiveCode.LIVE_ERROR.getCode(),String.format(LiveCode.LIVE_ERROR.getMessage(),response.getErrmsg()));
		}

		return response.getMediaId();
	}

	@Override
	public void synLiveStatus() {
		// 查询所有直播中未开始的直播列表
		BroadcastQuery query = new BroadcastQuery();
		List<String> vals = new ArrayList<>();
		vals.add("101");
		vals.add("102");
		query.liveStatus().in(vals);
		List<BroadcastEntity> list = list(query.toQueryWrapper());
		for (BroadcastEntity broadcast : list) {
			if (LocalDateTime.now().isAfter(broadcast.getEndTime())) {
				broadcast.setLiveStatus("103");
			}
			if (LocalDateTime.now().isAfter(broadcast.getBeginTime())
					&& LocalDateTime.now().isBefore(broadcast.getEndTime())) {
				broadcast.setLiveStatus("101");
			}
			if (LocalDateTime.now().isBefore(broadcast.getBeginTime())) {
				broadcast.setLiveStatus("102");
			}
			baseMapper.updateById(broadcast);
		}
	}

	@Override
	public List<String> busdIds(){
		return baseMapper.busdIds();
	}

}